<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%String path = request.getContextPath() ;%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %> 
<!DOCTYPE html>
<html lang="zh-CN" >
<head>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>保证金退回</title>
<jsp:include page="../../import.jsp" flush="true" />
<style type="text/css">
</style>
</head>
<body class="iframeBody">
<div class="Wrapper">
     <div class="fieldset1 tabel_col tabel_col_s clearFix">
         <div class="caption">
			<span class="title">基础信息 </span>
		</div>
		<div class="fieldBox col_33">
		   <div class="label">项目名称</div>
		   <div class="field">
              <span id="fncPrjNm" ></span>
           </div>
		</div>
		<div class="fieldBox col_33">
		   <div class="label">项目编号</div>
		   <div class="field">
              <span id="fncPrjIdShow" ></span>
           </div>
		</div>
		<div class="fieldBox col_33">
		   <div class="label">融资机构</div>
		   <div class="field">
              <span id="fncInsNm" ></span>
           </div>
		</div>
		<div class="fieldBox col_33">
		   <div class="label">已付保证金</div>
		   <div class="field">
              <span id="mrgnAtm" ></span>
           </div>
		</div>
		<div class="fieldBox col_33">
		   <div class="label">付款时间</div>
		   <div class="field">
             <span id="payTm"></span> 
           </div>
		</div>
		<div class="fieldBox col_33">
		   <div class="label">剩余保证金</div>
		   <div class="field">
		     <span id="srplsMrgnShow"></span>
           </div>
		</div>
	</div><br/>
	<div class="fieldset1 tabel_col_s clearFix" > <!-- fieldset1 tabel_col tabel_col_s clearFix -->
	   <div class="caption">
		   <span class="title" >抵扣记录 </span>
	   </div>
	  <div id="mrgnDeductligergrid" class="sq-grid"></div>
	</div><br/>
	<div class="fieldset1 tabel_col_s clearFix" > <!-- fieldset1 tabel_col tabel_col_s clearFix -->
	   <div class="caption">
		   <span class="title" >可分解还款列表 </span>
	   </div>
	  <div id="mrgnRepayligergrid" class="sq-grid"></div>
	   <div class="fieldBox col_100"  align="right">
		   <div class="label">合计</div>
		   <div class="field">
             <input name="totalAtm" id="totalAtm" type="text" class="ui-textbox" value="" disabled="disabled" >
           </div>
	   </div>
	</div>
	<!-- hidden -->
	<input name="srplsMrgn" id="srplsMrgn" type="hidden" class="ui-textbox" value=""  >
	<input name="fncPrjId" id="fncPrjId" type="hidden" class="ui-textbox" value=""  >
	<input name="prjLgcSn" id="prjLgcSn" type="hidden" class="ui-textbox" value="${prjLgcSn}"  >
	<input name="lgcId" id="lgcId" type="hidden" class="ui-textbox" value="${lgcId}"  >
	<div class="btnsBox" align="center">
		<span id="mrgn_deduct_info_add_btn_id"
			class="sq-button sq-button-round" onclick="save();">保存
		</span>
		<span id="mrgn_deduct_info_btn_id"
			class="sq-button sq-button-round" onclick="closeWind();">关闭
		</span>
	 </div>
</div>

<script type="text/javascript">
   $(function() {
	  initData();
	 });
   
   function initData(){
	  var lgcId=$("#lgcId").val();
	  var prjLgcSn=$("#prjLgcSn").val();
	  if(!prjLgcSn)  return;
	  var data=new Object();
	  data["lgcId"]=lgcId;
	  data["prjLgcSn"]=prjLgcSn;
	  var _url = '<%=path%>/rfbase/mrgnmanageinfo/getMrgnDeductInfoByLgcId.do';
	   AjaxUtils.ajaxPost(_url, data, callback);
	}
		
	  //新增回调
   function callback(msg){
	  if(msg.success == 1){
		  setData(msg.data);//设置数据
	  }else{
		  UIUtils.alertError(msg.info);
	  }
   }
		
	//设置页面数据
   function setData(data){
	    var mrgnManageInfo=data["mrgnManageInfo"];
	    var mrgnPayInfoList=data["mrgnTkOffInfoList"];
	    var mrgnTkOffInfoList=mrgnManageInfo.mrgnTkOffInfoList;
	    $("#fncInsNm").html(mrgnManageInfo.fncInsNm);
	    $("#srplsMrgnShow").html(moneyChange(mrgnManageInfo.srplsMrgn));
		$("#fncPrjNm").html(mrgnManageInfo.fncPrjNm);
		$("#fncPrjIdShow").html(mrgnManageInfo.fncPrjId);
		$("#mrgnAtm").html(moneyChange(mrgnManageInfo.mrgnAtm));
		$("#payTm").html(renderDateChange(mrgnManageInfo.payTm));
		$("#srplsMrgn").val(mrgnManageInfo.srplsMrgn);
		$("#fncPrjId").val(mrgnManageInfo.fncPrjId);
		$("#prjLgcSn").val(mrgnManageInfo.id);
		f_showMrgnDeductInfo(mrgnTkOffInfoList);
		f_showMrgnManageInfo(mrgnPayInfoList);
  };

  function f_getDetailData(listChange)
  {
      var data = { Rows: [] };
      for (var i = 0; i < listChange.length; i++)
      {
         data.Rows.push(listChange[i]);
      }
      return data;
  }
  
  //显示坐扣记录
  function f_showMrgnDeductInfo(mrgnTkOffInfoList)
  { 
	    $("#mrgnDeductligergrid").ligerGrid({
	        columns: [
	            { display: '申请抵扣金额',name: "thsRepyAmt", width: 150, render: function (rowdata, rowindex, value, column) { 
	            	var money =moneyChange(value);
                    return money;
            		},
        	      enabledSort:true},      
	            { display: '项目编号', name: 'payPrjId', width: 150},
	            { display: '期次', name: 'payPd', width: 150 },
	            { display: '抵扣项目', name: 'feeClsNm', width: 100,
	            	render: function (rowdata, rowindex, value){
	            		if(rowdata.feeClsCd==1){
	            		 return "本金";
	            		}else if(rowdata.feeClsCd==2){
	            		 return "利息";	
	            		}else if(rowdata.feeClsCd==3){
	            		 return "超额抵押";	
	            		}else if(rowdata.feeClsCd==4){
	            		 return "融资端";	
	            		}else if(rowdata.feeClsCd==5){
	            		 return "其他费用";	
	            		}else if(rowdata.feeClsCd==6){
	            		 return "剩余本金";	
	            		}
	            	}},
	            { display: '抵扣状态', name: '', width: 100,
	            	render: function (rowdata, rowindex, value){
            		 return "审核通过";
            	}}
	        ],
	        usePager:false,
	        data:f_getDetailData(mrgnTkOffInfoList),
	        width:'100%',
	        height:'auto',
	        heightDiff:-2,
	        checkbox:false,
	        rownumbers:true,
	    });
  }

   //显示还款List
    function f_showMrgnManageInfo(mrgnPayInfoList)
    { 
	    $("#mrgnRepayligergrid").ligerGrid({
	        columns: [
	            { display: '支付表逻辑编号',name: "payLgcSn", width: 150,hide: true},  
	            { display: '项目编号', name: 'payPrjId', width: 150},
	            { display: '期次', name: 'payPd', width: 150 },
	            { display: '应还项目', name: 'feeClsNm', width: 100,
	            	render: function (rowdata, rowindex, value){
	            		if(rowdata.feeClsCd==1){
	            		 return "本金";
	            		}else if(rowdata.feeClsCd==2){
	            		 return "利息";	
	            		}else if(rowdata.feeClsCd==3){
	            		 return "超额抵押";	
	            		}else if(rowdata.feeClsCd==4){
	            		 return "融资端";	
	            		}else if(rowdata.feeClsCd==5){
	            		 return "其他费用";	
	            		}else if(rowdata.feeClsCd==6){
	            		 return "剩余本金";	
	            		}
	            	}},
	            { display: '应还日期', name: 'payDt', width: 100, render:renderDate,},
	            { display: '应还金额', name: 'feeAmt', width: 100},
	            { display: '已还金额', name: 'paidUpAmt', width: 200},
	            { display: '剩余金额', name: 'arAmt', width: 100},
	            { display: '本次还款', name: 'thsRepyAmt', width: 200,value:"0",editor:{type:"number"}}
	        ],
	        usePager:false,
	        data:f_getDetailData(mrgnPayInfoList),
	        width:'100%',
	        height:'auto',
	        enabledEdit: true,
	        checkbox:true,
	        onBeforeEdit: f_onBeforeEdit,
	        onAfterEdit: f_onAfterEdit,
	        onBeforeCheckRow: function (checked, data, rowindex, rowobj)
            {
                if (data.arAmt == 0){
                	UIUtils.alertError("本期还款已结清，无需勾选还款!");
                    return false;
                }
                return true;
            },
            onSelectRow : function (rowdata, rowid, rowobj)
            {
                var manager = $("#mrgnRepayligergrid").ligerGetGridManager();
        		var aramt = rowdata.arAmt;
    	        manager.updateRow(rowdata,{
    	        	thsRepyAmt: aramt
    	        });
            },
	        frozenCheckbox:true
	    });
    }
	
    function f_onBeforeEdit(e)
    { 
        var manager = $("#mrgnRepayligergrid").ligerGetGridManager();
		var rowdata = manager.getRow(e.rowindex);
		if(rowdata.arAmt == 0){
			UIUtils.alertError("该期次还款已结清，无需修改!");
			return false;
		}
        if (e.column.name == "thsRepyAmt")
        {
            var rows = manager.getSelectedRows();
            if (!rows) { 
            	UIUtils.alertError("请选中该记录后，再编辑!");
            	return false; 
            }
            var arr = eval(rows);
            var rowchecked = false;//计算行记录是否选中
            
            for(var i=0;i<arr.length;i++){//定位选中结果集，根据剩余金额区分该行记录是否可以发起还款
            	if(e.rowindex == arr[i].__index){
            		rowchecked = true;
            		if(arr[i].arAmt == 0){
            			UIUtils.alertError("该期次还款已结清，无需修改!");
            			return false;
            		}else{
            			return true;
            		}
            	}
             }
            if(!rowchecked){
            	UIUtils.alertError("请选中该记录后，再编辑!");
            	return false;
            }
        }
        return false;
    }
    
    //编辑后事件
    function f_onAfterEdit(e){
    	var arAmt=e.record.arAmt;
    	if(e.value<0||e.value==null||e.value==""){
    		UIUtils.alertError("无效数字，请重新编辑！");
    	    return false;
    	}
    	var srplsMrgn=$("#srplsMrgn").val();
    	var thsRepyAmtSum=estimateEvent();
        var valueD=srplsMrgn-thsRepyAmtSum;
        $("#totalAtm").val(thsRepyAmtSum);
 	    if(valueD<0){
 		    UIUtils.alertError('“坐扣合计金额”大于“保证金剩余金额”，请重新填写');
   	        return false;
 	    }
 	    if(arAmt<e.value){
  		   UIUtils.alertError('“本次还款金额”大于“剩余应还金额”,，请重新填写！');
  	       return false;
  	    }
    }
    
    //计算选中还款项与保证金差值
    function  estimateEvent(){
    	var ligerForm = liger.get("mrgnRepayligergrid");
   	    var rows = ligerForm.getCheckedRows();
   	    var thsRepyAmtSum = 0;
         $(rows).each(function()
	      {
   		      thsRepyAmtSum += this.thsRepyAmt;
	      });
   	    return thsRepyAmtSum;
    }
 
    //提交
    function save() {
 	   var ligerForm = liger.get("mrgnRepayligergrid");
 	   var deductOprtRows = ligerForm.getCheckedRows();//获取选择行的数据
 	  //判断每行剩余金额大于还款金额
 	  for(var j=0;j<deductOprtRows.length;j++){
 		  if(deductOprtRows[j].arAmt<deductOprtRows[j].thsRepyAmt){
 			 UIUtils.alertError("存在“本次还款金额”大于“剩余金额”，请重新填写");
  	         return false;
 		  }
 	  }
 	  //判断还款金额是否大于保证金剩余金额
 	  var srplsMrgn=$("#srplsMrgn").val();
  	  var thsRepyAmtSum=estimateEvent();
      var valueD=srplsMrgn-thsRepyAmtSum;
	    if(valueD<0){
		    UIUtils.alertError("“还款金额总和”大于“保证金剩余金额”，请重新选择");
 	        return false;
	    }
	   $("#totalAtm").val(thsRepyAmtSum);
	   
	   //判断是否勾选
 	   if (thsRepyAmtSum==''||thsRepyAmtSum==null||thsRepyAmtSum==0) {
 		  UIUtils.alertError("请先填写还款，再提交！");
   	      return false;
 	   }
 	  
	  var fncPrjId= $("#fncPrjId").val();
      var deductOprtArray=JSON.stringify(deductOprtRows);
      var data=new Object();
      data["deductOprtArray"]=deductOprtArray;
      data["txnAmt"]=thsRepyAmtSum;
      data["srplsAtm"]=valueD;
      data["fncPrjId"]=fncPrjId;
      data["prjLgcSn"]=$("#prjLgcSn").val();
      data["mgtLgcSn"]=$("#lgcId").val();
      //编辑URL
      var url='<%=path%>/rfbase/mrgnmanageinfo/updateDeductOprt.do';
      if( data["mgtLgcSn"]==null|| data["mgtLgcSn"]==''){
    	  //添加URL
    	  var url='<%=path%>/rfbase/mrgnmanageinfo/addDeductOprt.do';
      }
      
      $.ajax({
   		type: 'post',
   		dataType:'json', 
   		data:data,
   		url: url,
   		beforeSend: function(){
   	       wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING ,SQ_type: "waitting" });
   	     },
   		success:function(msg){
   			 wait_dialog.close();
   			 var e=msg.success;
   			 if(msg.success == 1){
   				var lgcId=$("#lgcId").val();
   				if(lgcId==null||lgcId==''){
   					$("#lgcId").val(msg.data);
   					startFlow();
				 }else{
					$.ligerDialog.success(msg.info);
				 }
					 
   			 }else{
   				 $.ligerDialog.error(msg.info);
   			 }
   		}
     });
   }
	  
  //发起审核流程
  function startFlow(){
     var _id=$("#lgcId").val();
     if(!_id){
		   UIUtils.alertError("请先保存再发起流程！");
		   return ;
		}
	 var modelTyp ="R009";//流程业务分类-再融资保证金退回流程
	 if(StringUtils.isEmpty(modelTyp)){
		console.log("modelTyp is null");
		return;
	 }
     var flowDialog = $.ligerDialog.SQopen({
         url: '<%=path%>/flow/flow/toForStartListPage.do?modelTyp='+modelTyp,
         width: 700,
         height:400,
         title : '请选择要发起的流程',allowClose:false,
         buttons: [{
 	                text: "确定", type: 'ok', cls: 'l-dialog-btn-ok',
 	                onclick: function (item, Dialog) {
 	                    if (Dialog.onOk) Dialog.onOk();
 	                }
 	            }, {
 	                text: "取消", type: 'cancel', cls: 'l-dialog-btn-no',
 	                onclick: function (item, Dialog) {
 	                    if (Dialog.onCancel) Dialog.onCancel();
 	                }
 	            }
 	        ],
         onClose: function () {
         	var json = flowDialog._DATA;
         	console.log(json);
         	if(!json){
         		closeWind();
             	return;
         	}
         	var wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting",onClose: function () {}});
     		$.ajax({
         		type: 'post',
         		dataType:'json',
         		data:{
         			id:_id,
         			procDefKey:json.procDefKey,
         			procDefId:json.procDefId,
         			procNo:json.procNo
         		},
         		url: '<%=path%>/rfbase/mrgnmanageinfo/addMrgnDeductFlowStart.do',
         		success:function(msg){
         			wait_dialog.close();
         			 if(msg.success == 1){
       					 UIUtils.alertSuccessHold1(msg.info);
       					 closeWind();
 	           			 }else{
 	          				UIUtils.alertErrorHold1(msg.info);
 	           		}
         		}
         	});
         }
     });
   }	  
    
  //关闭页面
  function closeWind(){
	var selectedTabId = parent.mainApp.parentTab.selectedTabId;
	var lastTab = parent.tabItems[0];
	parent.mainApp.parentTab.reload(lastTab.tabid);
	parent.mainApp.parentTab.removeTabItem(selectedTabId);
	parent.grid.reload();
  }
  
 //格式化时间
 function renderDateChange(value){
	var dateStr = "";
	if(null != value &&  ""!= value){
		var date = new Date(value);
		dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DDHHMMSS);
	}
	return dateStr;
 } 
 
//格式化时间
 function renderDate(rowdata, index, value){
	var dateStr = "";
	if(null != value){
		var date = new Date(value);
		dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DDHHMMSS);
	}
	return dateStr;
 }
 
//格式化金额
 function moneyChange(value) { 
		var h = '';
			if(value&&value!="null"){
		    h+=fmoney(value, 2);
			}else{
			h+="0.00";
			}
         return h;
		}
 
 //格式化金额
 function fmoney(s, n)   
	{   
	   n = n > 0 && n <= 20 ? n : 2;   
	   s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";   
	   var l = s.split(".")[0].split("").reverse(),   
	   r = s.split(".")[1];   
	   t = "";   
	   for(i = 0; i < l.length; i ++ )   
	   {   
	      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");   
	   }   
	   return t.split("").reverse().join("") + "." + r;   
	} 
 
</script>

</body>
</html>
